﻿
using LMM_Editor.Classes.Entities;
using LMM_Editor.Classes.System.Tools;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LMM_Editor.Classes.System
{
    public class ToolSelectEntity : Tool
    {
        public IEntity selectedEntity;
        public Point mouseDownPoint;

        public ToolSelectEntity()
        {
            name = "Tool_SelectEntity";
            description = "Selects an instance of an entity in the view.";
            tooltype = ToolType.Select;
        }

        public void resetSelectedEntity()
        {
            Data.propertiesGrid.SelectedObject = null;
            if (selectedEntity != null)
            {
                selectedEntity.deselect();
            }
            selectedEntity = null;
        }

        public override IEntity useTool(double x, double y, Control parent, IEntity entity)
        {
            resetSelectedEntity();
            return null;
        }

        public override IEntity onClick(object sender, ClickEventArgs e)
        {
           // return useTool((double)e.x, (double)e.y, e.entity.component, e.entity);
            mouseDownPoint = new Point(e.x, e.y);

            // get the entity at the mouse
            resetSelectedEntity();

            if (e.entity != null)
            {
                Control c = e.entity.component;
                selectedEntity = e.entity;
                Data.propertiesGrid.SelectedObject = selectedEntity.propertyWrapper;
                e.entity.select();
                Data.propertiesGrid.Refresh();
                return e.entity;
            }

            return null;
        }

        public IEntity onClickRelease(object sender, ClickEventArgs args)
        {
            useToolEnd(args.x, args.y, args.entity);
            return null;
        }

        public void useToolMove(object sender, MouseEventArgs e)
        {
        }
        
        public void useToolEnd(double x, double y, IEntity entity)
        {
            if (selectedEntity != null)
            {
                Control c = (Control)selectedEntity.component;
                Point p = new Point((int)x - mouseDownPoint.X, (int)y - mouseDownPoint.Y);
                c.Left += p.X;
                c.Top += p.Y;
            }
        }

        public override void useToolEndConvert(object sender, MouseEventArgs e)
        {
            IEntity entity = EntityManager.findEntity((Control)sender);
            onClickRelease(sender, getClickEventArgs(e, entity));
        }
    }
}
